<?php
require_once __DIR__ . '/../models/UserPost.php';

class UserPostController
{
	private $db;
	private $userPostModel;

	public function __construct($db)
	{
		$this->db = $db;
		$this->userPostModel = new UserPost($db);
	}

	/**
	 * 获取用户攻略帖
	 */
	public function getUserPosts()
	{
		try {
			$userId = $_GET['user_id'] ?? null;

			// 获取用户帖子数据
			$posts = $this->userPostModel->getPostsWithUserInfo($userId);

			$this->sendResponse($posts);
		} catch (Exception $e) {
			$this->handleError($e);
		}
	}

	/**
	 * 获取用户讨论贴
	 */
	public function getUserTopics()
	{
		try {
			$userId = $_GET['user_id'] ?? null;

			// 获取用户帖子数据
			$posts = $this->userPostModel->getTopicsWithUserInfo($userId);

			$this->sendResponse($posts);
		} catch (Exception $e) {
			$this->handleError($e);
		}
	}

	/**
	 * 删除用户攻略帖
	 */
	public function deleteUserPost()
	{
		try {
			// 从请求体中获取 JSON 数据
			$input = json_decode(file_get_contents('php://input'), true);

			$postId = $input['post_id'] ?? null;
			$userId = $input['user_id'] ?? null; // 可选：验证用户权限

			if (!$postId) {
				throw new Exception("帖子ID不能为空");
			}

			// 删除帖子
			$result = $this->userPostModel->deletePost($postId, $userId);

			$this->sendResponse(['success' => $result]);
		} catch (Exception $e) {
			$this->handleError($e);
		}
	}

	/**
	 * 删除用户讨论帖
	 */
	public function deleteUserTopic()
	{
		try {
			// 从请求体中获取 JSON 数据
			$input = json_decode(file_get_contents('php://input'), true);

			$topicId = $input['topic_id'] ?? null;
			$userId = $input['user_id'] ?? null; // 可选：验证用户权限

			if (!$topicId) {
				throw new Exception("讨论帖ID不能为空");
			}

			// 删除讨论帖
			$result = $this->userPostModel->deleteTopic($topicId, $userId);

			$this->sendResponse(['success' => $result]);
		} catch (Exception $e) {
			$this->handleError($e);
		}
	}

	/**
	 * 统一响应方法
	 */
	private function sendResponse($data)
	{
		header('Content-Type: application/json');

		if (empty($data)) {
			http_response_code(200);
			echo json_encode([
				'status' => 'success',
				'count' => 0,
				'data' => []
			], JSON_UNESCAPED_UNICODE);
			return;
		}

		http_response_code(200);
		echo json_encode([
			'status' => 'success',
			'count' => count($data),
			'data' => $data
		], JSON_UNESCAPED_UNICODE);
	}

	/**
	 * 统一错误处理
	 */
	private function handleError($e)
	{
		error_log("[UserPost Controller] 错误: " . $e->getMessage());
		http_response_code(500);
		echo json_encode([
			'status' => 'error',
			'message' => $e->getMessage()
		], JSON_UNESCAPED_UNICODE);
	}
}